package com.jeecms.wicool.action.groupBuy;

import com.jeecms.wicool.entity.groupBuy.GroupBuy;
import com.jeecms.wicool.entity.groupBuy.GroupBuySpecification;
import com.jeecms.wicool.manager.groupBuy.GroupBuyMng;
import com.jeecms.wicool.manager.groupBuy.GroupBuySpecificationMng;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by cuiyanlei on 15/6/12.
 */
@Controller
@RequestMapping("/groupBuySepc")
public class GroupBuySpecificationAct {

    @RequestMapping("v_to_edit_specification.do")
    public String list(Integer groupBuyId, ModelMap model) {
        List<GroupBuySpecification> specifications = manager.getAll(groupBuyId);
        model.addAttribute("specifications", specifications);
        model.addAttribute("groupBuyId", groupBuyId);
        return "group_buy/edit_group_buy_spec";
    }

    @RequestMapping("o_update.do")
    public String update(Integer groupBuyId, Integer[] boundaryCounts, Double[] prices, ModelMap model) {
        GroupBuy groupBuy = groupBuyMng.findById(groupBuyId);
        for (GroupBuySpecification specification : groupBuy.getSpecifications()) {
            specification.setGroupBuy(null);
            manager.deleteById(specification.getId());
        }
        if (boundaryCounts != null) {
            for (int i = 0; i < boundaryCounts.length; i++) {
                Integer boundaryCount = boundaryCounts[i];
                Double price = prices[i];
                GroupBuySpecification specification = new GroupBuySpecification(null, boundaryCount, new BigDecimal(price), groupBuy);
                manager.save(specification);
            }
        }
        model.addAttribute("message", "global.success");
        return list(groupBuyId, model);
    }

    @Autowired
    private GroupBuySpecificationMng manager;

    @Autowired
    private GroupBuyMng groupBuyMng;
}
